//
//  VipCardLeaveViewController.m
//  fitnessmanage
//
//  Created by 众拳科技 on 2017/11/1.
//  Copyright © 2017年 zongquankeji. All rights reserved.
//  请假记录

#import "VipCardLeaveViewController.h"
#import "VipCardLeaveTableViewCell.h"
#import "AddLeaveViewController.h"
#import "AdvanceDestoryLeaveViewController.h"
#import "YCXMenu.h"

@interface VipCardLeaveViewController ()<UITableViewDelegate,UITableViewDataSource>{
    
    int startIndex;
    
    int pageSize;
}

@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataSource;

@property (nonatomic , strong) NSMutableArray *rightItems;

@property(nonatomic,strong)NoDataView *noDataView;

@end

@implementation VipCardLeaveViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
 
    self.title = @"请假记录";
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"add"]                                                                               imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
    
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateNormal];
    
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    [self createSubView];
    
    [NotificationCenter addObserver:self selector:@selector(loadStartData) name:@"ReloadLeave" object:nil];
}

-(void)createSubView{
    
    self.view.backgroundColor = BackGroundColor;
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.estimatedRowHeight = 200;
    [tableView registerClass:[VipCardLeaveTableViewCell class] forCellReuseIdentifier:@"VipCardLeaveTableViewCell"];
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    tableView.backgroundColor = CSClearColor;
    [self.view addSubview:tableView];
    [tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(self.view);
    }];
    self.tableView = tableView;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.automaticallyHidden = YES;
    
    
    MyTableHead *mj_head = [MyTableHead headerWithRefreshingTarget:self refreshingAction:@selector(loadStartData)];
    tableView.mj_header = mj_head;
    tableView.mj_footer = footer;
    [tableView.mj_header beginRefreshing];
}

#pragma mark 下拉
-(void)loadStartData{
    
    startIndex = 1;
    
    pageSize = 20;
    
    [self loadData];
}

#pragma mark 上拉
-(void)loadMoreData{
    
    startIndex = startIndex + 1;
    
    [self loadData];
}

-(void)loadData{
    
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    
    VenueModel *venueModel = [VenueModel venue];
    
//    [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"ShopID"] forKey:@"ShopID"];
//    
//    [params setObject:self.vipCardModel.ID forKey:@"MemberCardID"];
//    
//    [params setObject:[NSString stringWithFormat:@"%d",startIndex] forKey:@"page"];
//    
//    [params setObject:[NSString stringWithFormat:@"%d",pageSize] forKey:@"rows"];
//    
    [HTTPTool GET:Get_LeaveListData parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSMutableArray *resultArray = [responseObject objectForKey:@"rows"];
                  
                  if (resultArray.count > 0) {
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshing];
                  }
                  else{
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshingWithNoMoreData];
                  }
                  
                  self.noDataView = [NoDataView shareInstance];
                  
                  [self.noDataView hideInView:self.view];
                  
                  if (startIndex == 1) {
                      
                      self.dataSource = [NSMutableArray arrayWithArray:resultArray];
                      
                      if (self.dataSource.count == 0) {
                          
                          self.noDataView = [NoDataView shareInstance];
                          
                          [self.noDataView showInView:self.view];
                      }
                  }
                  else{
                      
                      [self.dataSource addObjectsFromArray:resultArray];
                  }
                  
                  [self.tableView reloadData];
              }
              
          }
     
          failure:^(NSError *error){
              
              [self.tableView.mj_header endRefreshing];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}


#pragma mark UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VipCardLeaveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"VipCardLeaveTableViewCell"];
    
    
    NSDictionary *dict = [self.dataSource objectAtIndex:indexPath.section];
    
    
    cell.reasonLabel.text = [dict objectForKey:@"Reason"];
    
    //@"时间：2017-11-30 至 2017-12-01";
    
    cell.timeLabel.text = [NSString stringWithFormat:@"时间：%@ 至 %@",[dict objectForKey:@"BeginDate"],[dict objectForKey:@"EndDate"]];
    
    //收费：12元
    NSString *fee = [NSString stringWithFormat:@"%@",[dict objectForKey:@"Fee"]];
    
    fee = [fee isEmptyString]?@"0":fee;
    
    cell.chargeLabel.text = [NSString stringWithFormat:@"收费：%@元",fee];
    
    //备注：
    NSString *memo = [NSString stringWithFormat:@"%@",[dict objectForKey:@"Memo"]];
    
    cell.noteLabel.text = [NSString stringWithFormat:@"备注：%@",memo];
    
    cell.rightBtn.tag = indexPath.section;
    
    [cell.rightBtn addTarget:self action:@selector(cellBtnClick:)];
    
    
    NSString *statue = [dict objectForKey:@"Status"];
    
    if ([statue isEqualToString:@"进行中"]) {
        
        cell.typeImageView.image = [UIImage imageNamed:@"card_label_ing"];
    }
    else{
        
        cell.typeImageView.image = [UIImage imageNamed:@"card_label_end"];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark UITableViewDelegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.00001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 10;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}

#pragma mark 提前销假
-(void)cellBtnClick:(UIButton *)sender{
    
    
    NSDictionary *dict = [self.dataSource objectAtIndex:sender.tag];
    
    NSString *statue = [dict objectForKey:@"Status"];
    
    if (![statue isEqualToString:@"进行中"]) {
        
        return;
    }
        
    if ([YCXMenu isShow]){
        
        [YCXMenu dismissMenu];
    }
    else{
        
        __weak typeof(self)weakSelf = self;
        
        [YCXMenu setHasShadow:YES];
        [YCXMenu setBackgrounColorEffect:YCXMenuBackgrounColorEffectSolid];
        [YCXMenu setTintColor:CSWhiteColor];
        [YCXMenu setSelectedColor:CSClearColor];
        [YCXMenu setSeparatorColor:[[UIColor grayColor] colorWithAlphaComponent:0.5]];
        //        [YCXMenu setMenuItemMarginY:15];
        [YCXMenu setTitleFont:[UIFont systemFontOfSize:16.0]];
        NSInteger section = sender.tag;
        CGRect rectInTableView = [weakSelf.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section]];
        
        
        CGRect rect = [weakSelf.tableView convertRect:rectInTableView toView:[weakSelf.tableView superview]];
        
        [YCXMenu showMenuInView:[UIApplication sharedApplication].keyWindow fromRect:CGRectMake(weakSelf.view.frame.size.width - 50, rect.origin.y +adaptNavagationBar + 45, 50, 0) menuItems:weakSelf.rightItems selected:^(NSInteger index, YCXMenuItem *item) {
            
            if ([item.title isEqualToString:@"删除请假"]) {
                
                UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否确删除" message:@"" preferredStyle:UIAlertControllerStyleAlert];//
                
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                    
                    NSString *leaveId = [dict objectForKey:@"ID"];
                    
                    [weakSelf deleteWithId:leaveId];
                }];
                
                [alertController addAction:cancelAction];
                
                [alertController addAction:okAction];
                
                [self presentViewController:alertController animated:YES completion:nil];
            }
            else{
     
                AdvanceDestoryLeaveViewController *advanceDestoryVC = [[AdvanceDestoryLeaveViewController alloc] init];
            
                advanceDestoryVC.leaveDict = dict;
                
                [weakSelf.navigationController pushViewController:advanceDestoryVC animated:YES];
            }
            
            NSLog(@"%@",item);
        }];
    }
}


#pragma mark 删除
-(void)deleteWithId:(NSString *)leaveId{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setObject:leaveId forKey:@"ID"];
    
    [MBProgressHUD showMessage:@"请求中..." toView:self.view];
    
    [HTTPTool POSTRaw:Post_Leave_DeleteLeave parameters:params
     
              success:^(id responseObject){
                  
                  [MBProgressHUD hideHUDForView:self.view];
                  
                  if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                      
                      [MBProgressHUD showText:@"删除成功"];
                      
                      [self loadData];
                  }
                  
              }
     
              failure:^(NSError *error){
                  
                  [MBProgressHUD hideHUDForView:self.view];
              }];
    
}

#pragma mark 添加
-(void)rightBtnClick{
    
    AddLeaveViewController *addLeaveVC = [[AddLeaveViewController alloc] init];
    
    addLeaveVC.memberCardId = self.vipCardModel.ID;
    
    [self.navigationController pushViewController:addLeaveVC animated:YES];
}

-(NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        
        _dataSource = [[NSMutableArray alloc] init];
    }
    
    return _dataSource;
}

- (NSMutableArray *)rightItems {
    if (!_rightItems) {
        
        //set item
        _rightItems = [@[
                         [YCXMenuItem menuItem:@"删除请假"
                                         image:nil
                                           tag:100
                                      userInfo:@{@"title":@"Menu"}],
                         [YCXMenuItem menuItem:@"提前销假"
                                         image:nil
                                           tag:101
                                      userInfo:@{@"title":@"Menu"}],
                         
                         ] mutableCopy];
    }
    return _rightItems;
}

-(void)dealloc{
    
    [NotificationCenter removeObserver:self];
}

@end
